import { useState, useEffect, Suspense } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Layout, Menu, Breadcrumb, Avatar, Tooltip } from "antd";
import { UserOutlined, LogoutOutlined } from "@ant-design/icons";
import { Outlet } from "react-router-dom";
import "./Layout.scss";
import { http } from "../utils/request";

const { Header, Sider, Content } = Layout;

// 添加菜单项类型定义
interface MenuApiData {
  id: number;
  parentId: number;
  menuName: string;
  url: string;
  description?: string;
  editAble: number;
  menuList?: MenuApiData[];
  component?: string;
}

// 用户信息类型定义
interface UserInfo {
  id: number;
  username: string;
  fullName: string;
  role: {
    id: number;
    name: string;
    menuList: MenuApiData[];
  };
}

const MainLayout = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [menuItems, setMenuItems] = useState<MenuApiData[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);

  const [currentTime, setCurrentTime] = useState<string>(() =>
    new Date().toLocaleString()
  );

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date().toLocaleString());
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  // 加载菜单数据和用户信息的函数
  const loadMenuData = async () => {
    const userId = localStorage.getItem("userId");
    if (!userId) {
      console.error("未找到用户ID");
      return;
    }

    try {
      // 调用接口获取用户信息
      const result = await http.get(`/api/user/userInfo?id=${userId}`);

      if (+result.status === 200 && result.data) {
        setUserInfo(result.data);
        localStorage.setItem("userInfo", JSON.stringify(result.data));
        // 直接使用接口返回的 menuList 数据
        const menuData = result.data.role?.menuList || [];
        setMenuItems(menuData);

        // 设置默认选中的菜单
        if (location.pathname !== "/login") {
          setSelectedKeys([location.pathname]);
        }
      } else {
        console.error("获取用户信息失败:", result.message);
      }
    } catch (error) {
      console.error("获取用户信息失败:", error);
    }
  };

  useEffect(() => {
    loadMenuData();
  }, []);

  // 监听路径变化，更新选中的菜单
  useEffect(() => {
    if (location.pathname !== "/login") {
      setSelectedKeys([location.pathname]);
    }
  }, [location.pathname]);

  // 添加监听用户信息更新事件
  useEffect(() => {
    const handleUserInfoUpdate = (event: CustomEvent) => {
      console.log("收到用户信息更新事件:", event.detail);

      // 直接使用事件传递的新用户信息更新状态
      setUserInfo(event.detail);

      // 更新菜单数据
      const menuData = event.detail.role?.menuList || [];
      setMenuItems(menuData);

      console.log("菜单已更新:", menuData);
    };

    // 监听自定义事件
    window.addEventListener(
      "userInfoUpdated",
      handleUserInfoUpdate as EventListener
    );

    // 清理事件监听器
    return () => {
      window.removeEventListener(
        "userInfoUpdated",
        handleUserInfoUpdate as EventListener
      );
    };
  }, []);

  // 监听菜单更新事件
  useEffect(() => {
    const handleMenuUpdate = () => {
      console.log("收到菜单更新事件，重新加载菜单");
      loadMenuData();
    };

    window.addEventListener("menuUpdated", handleMenuUpdate);
    return () => {
      window.removeEventListener("menuUpdated", handleMenuUpdate);
    };
  }, []);

  // 添加根据路径查找菜单项的函数
  const findMenuByPath = (
    menus: MenuApiData[],
    targetPath: string
  ): MenuApiData[] => {
    for (const menu of menus) {
      if (menu.url === targetPath) {
        return [menu];
      }

      if (menu.menuList && menu.menuList.length > 0) {
        const childPath = findMenuByPath(menu.menuList, targetPath);
        if (childPath.length > 0) {
          return [menu, ...childPath];
        }
      }
    }
    return [];
  };

  // 生成面包屑 - 修改为使用菜单数据
  const generateBreadcrumbItems = () => {
    const currentPath = location.pathname;
    const items: { title: string; key: string }[] = [];

    // 首页面包屑
    items.push({
      title: "首页",
      key: "home",
    });

    // 如果不是首页，查找当前路径的菜单层级
    if (currentPath !== "/home") {
      const menuPath = findMenuByPath(menuItems, currentPath);

      if (menuPath.length > 0) {
        // 添加菜单路径到面包屑，使用 menuName 字段
        menuPath.forEach((menu, index) => {
          items.push({
            title: menu.menuName,
            key: `menu-${index}`,
          });
        });
      } else {
        // 如果找不到对应菜单，使用路径生成
        const pathSegments = currentPath.split("/").filter(Boolean);
        if (pathSegments.length > 0) {
          const lastSegment = pathSegments[pathSegments.length - 1];
          let displayName = lastSegment.replace(/-/g, " ");

          // 尝试在所有菜单中查找包含此路径段的菜单
          const allMenusFlat = (menus: MenuApiData[]): MenuApiData[] => {
            let result: MenuApiData[] = [];
            menus.forEach((menu) => {
              result.push(menu);
              if (menu.menuList && menu.menuList.length > 0) {
                result = result.concat(allMenusFlat(menu.menuList));
              }
            });
            return result;
          };

          const allMenus = allMenusFlat(menuItems);
          const foundMenu = allMenus.find(
            (menu) =>
              menu.url.includes(lastSegment) || menu.component === lastSegment
          );

          if (foundMenu) {
            displayName = foundMenu.menuName;
          }

          items.push({
            title: displayName,
            key: "current",
          });
        }
      }
    }

    return items;
  };

  // 处理菜单点击
  const handleMenuClick = ({ key }: { key: string }) => {
    // 更新选中的菜单键
    setSelectedKeys([key]);

    if (key && key !== location.pathname) {
      navigate(key, { replace: false });
    } else {
      console.log("路径相同，跳过导航");
    }
  };

  // 处理菜单展开/收起
  const handleOpenChange = (keys: string[]) => {
    setOpenKeys(keys);
  };

  // 处理退出登录
  const handleLogout = () => {
    // 清理所有存储的信息
    localStorage.removeItem("token");
    localStorage.removeItem("userId");
    localStorage.removeItem("roleId");
    navigate("/login");
  };

  // 修改渲染菜单项的函数，添加 tooltip 支持
  const renderMenuItem = (menu: MenuApiData, level: number = 1): any => {
    const hasChildren = menu.menuList && menu.menuList.length > 0;

    // 根据菜单名称长度判断是否需要 tooltip
    const needTooltip = menu.menuName.length > (level === 1 ? 8 : 6);

    if (hasChildren) {
      return (
        <Menu.SubMenu
          key={menu.url}
          title={
            needTooltip ? (
              <Tooltip title={menu.menuName} placement="right">
                <span
                  onClick={(e) => {
                    e.stopPropagation();
                    handleMenuClick({ key: menu.url });
                  }}
                  style={{
                    cursor: "pointer",
                    display: "inline-block",
                    maxWidth: level === 1 ? "140px" : "120px",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  }}
                >
                  {menu.menuName}
                </span>
              </Tooltip>
            ) : (
              <span
                onClick={(e) => {
                  e.stopPropagation();
                  handleMenuClick({ key: menu.url });
                }}
                style={{ cursor: "pointer" }}
              >
                {menu.menuName}
              </span>
            )
          }
        >
          {menu.menuList!.map((subMenu: MenuApiData) =>
            renderMenuItem(subMenu, level + 1)
          )}
        </Menu.SubMenu>
      );
    }

    return (
      <Menu.Item key={menu.url}>
        {needTooltip ? (
          <Tooltip title={menu.menuName} placement="right">
            <span
              style={{
                display: "inline-block",
                maxWidth: level === 1 ? "140px" : "120px",
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}
            >
              {menu.menuName}
            </span>
          </Tooltip>
        ) : (
          menu.menuName
        )}
      </Menu.Item>
    );
  };

  return (
    <div className="layout-wrapper">
      <Sider className="layout-sider" width={280}>
        <div className="logo">
          <h1>电网管理系统</h1>
        </div>
        <Menu
          className="menu"
          mode="inline"
          selectedKeys={selectedKeys}
          openKeys={openKeys}
          onClick={handleMenuClick}
          onOpenChange={handleOpenChange}
          theme="dark"
        >
          {/* 渲染从接口获取的菜单列表 */}
          {menuItems.map((menu) => renderMenuItem(menu))}

          {/* 如果没有菜单权限，至少显示首页 */}
          {menuItems.length === 0 && <Menu.Item key="/home">首页</Menu.Item>}
        </Menu>
      </Sider>
      <Layout>
        <Header className="layout-header">
          <div className="header-left">
            <Breadcrumb>
              {generateBreadcrumbItems().map((item) => (
                <Breadcrumb.Item key={item.key}>{item.title}</Breadcrumb.Item>
              ))}
            </Breadcrumb>
          </div>
          <div className="header-right">
            <div className="user-info">
              <span className="current-time" style={{ marginRight: 12 }}>
                {currentTime}
              </span>
              <Avatar className="avatar" icon={<UserOutlined />} />
              <span className="username">{userInfo?.fullName || "用户"}</span>
            </div>
            <span className="logout-btn" onClick={handleLogout}>
              <LogoutOutlined /> 退出
            </span>
          </div>
        </Header>
        <Content className="layout-content">
          <div className="content-wrapper">
            <Suspense fallback={<div>加载中...</div>}>
              <Outlet />
            </Suspense>
          </div>
        </Content>
      </Layout>
    </div>
  );
};

export default MainLayout;
